from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import text
from flask_jwt_extended import JWTManager
import re

db = SQLAlchemy()
jwt = JWTManager()


def run_sql_file(filename):
    with open(filename, 'r', encoding='utf-8') as file:
        sql_script = file.read()

    # 去除 SQL 注释
    sql_script = re.sub(r'--.*', '', sql_script)
    sql_script = re.sub(r'/\*.*?\*/', '', sql_script, flags=re.DOTALL)

    # 按分号分割 SQL 脚本为多个语句
    statements = sql_script.split(';')

    # 使用 db.engine.connect() 获取连接对象并执行 SQL 脚本
    with db.engine.connect() as connection:
        for statement in statements:
            # 去除空白字符
            statement = statement.strip()
            if statement:
                try:
                    # 使用 text 函数包装 SQL 语句
                    connection.execute(text(statement))
                except Exception as e:
                    print(f"执行 SQL 语句时出错: {statement}\n错误信息: {e}")


